package com.load.ctrls.imp;

import static com.load.parsers.ClassParser.*;
import japa.parser.ParseException;
import japa.parser.ast.CompilationUnit;

import java.util.*;

import org.apache.log4j.Logger;
import org.tmatesoft.svn.core.*;

import com.database.objects.*;
import com.database.objects.Class;
import com.load.ctrls.IProjectCtrl;
import com.load.factories.*;
import com.load.objects.MySVNDirEntry;
import com.load.parsers.MethodParser;
import com.load.utils.SVNUtil;

public class ProjectCtrl implements IProjectCtrl {

	private static final long serialVersionUID = 9181592505274695697L;

	private static Logger logger = Logger.getLogger("load.repository");

	@Override
	public void completeData(Project project) {
		try {
			VersionRepository repository = project.getVersionRepository();
			List<MySVNDirEntry> currentJavaEntries = SVNUtil.getCurrentJavaEntries(repository.getSvnRepository(), "");
			logger.info("CURRENT ENTRIES: " + currentJavaEntries.size());

			int index = 1;
			List<FileOO> files = new ArrayList<FileOO>();
			for (MySVNDirEntry entry : currentJavaEntries) {
				File file = FileFactory.createFile(repository.getSvnRepository(), entry);
				logger.info("FILE: " + index + " - " + entry.getPath());
				FileOO fileOO = (FileOO) file;
				configureFileOO(fileOO, index);
				files.add(fileOO);
				index++;
			}

			Data data = DataFactory.createData(project, files);
			project.setData(data);
		} catch (SVNException e) {
			logger.error("ERROR: Obtaining files in current entries");
			e.printStackTrace();
		}
	}

	private void configureFileOO(FileOO fileOO, int index) {
		if (fileOO.isFile()) {
			try {
				CompilationUnit compilation = fileOO.buildCompilation();
				addClasses(compilation, fileOO);

				logger.info("FILE: " + index + " - " + fileOO.getChilds().size() + " classes");
				for (Element<?, ?> childClass : fileOO.getChilds()) {
					MethodParser.addMethods(compilation, (Class) childClass);

					logger.info("FILE: " + index + " - CLASS: " + childClass.getLabel());
					for (Element<?, ?> childMethod : childClass.getChilds()) {
						((Method) childMethod).addLinesUsingContent();
					}
				}
			} catch (ParseException e) {
				logger.error("ERROR: Obtaining compilation unit for file " + fileOO.getPath());
				e.printStackTrace();
			}
		}
	}

}